package com.dongrj.framework.starter.log.utils;

import com.dongrj.framework.core.constant.Constant;
import com.dongrj.framework.core.utils.StringUtils;
import com.dongrj.framework.starter.log.constant.LogConstant;
import org.slf4j.MDC;

import javax.servlet.http.HttpServletRequest;
import java.util.function.Supplier;

/**
 * @author dongrongjun
 * @date 2021/04/14
 */
public class TraceIdUtils {

    /**
     * 获取Request Header中的traceId
     */
    public static String getTraceId() {
        return getTraceId("");
    }

    /**
     * 获取Request Header中的traceId
     */
    public static String getTraceId(String dfValue) {
        return StringUtils.defaultIfEmpty(MDC.get(LogConstant.MDCField.TRACE_ID), StringUtils::randomUUID);
    }


    /**
     * 获取Request Header中的traceId
     *
     * @param request 请求
     */
    public static String getTraceId(HttpServletRequest request) {
        return getTraceId(request, "");
    }

    /**
     * 获取Request Header中的traceId
     *
     * @param request 请求
     * @param dfValue 默认值
     */
    public static String getTraceId(HttpServletRequest request, String dfValue) {
        String header = request.getHeader(Constant.TRACE_ID);
        if (StringUtils.isEmpty(header)) {
            return dfValue;
        }
        return header;
    }

    /**
     * 获取Request Header中的traceId
     *
     * @param request 请求
     */
    public static void setTraceId(HttpServletRequest request) {
        setTraceId(request, "");
    }

    /**
     * 获取Request Header中的traceId
     *
     * @param request 请求
     * @param dfValue 默认值
     */
    public static void setTraceId(HttpServletRequest request, String dfValue) {
        String header = request.getHeader(Constant.TRACE_ID);
        if (StringUtils.isEmpty(header)) {
            MDC.put(LogConstant.MDCField.TRACE_ID, dfValue);
        } else {
            MDC.put(LogConstant.MDCField.TRACE_ID, header);
        }
    }

    /**
     * 获取Request Header中的traceId
     *
     * @param request         请求
     * @param dfValueSupplier 默认值
     */
    public static void setTraceId(HttpServletRequest request, Supplier<String> dfValueSupplier) {
        String header = request.getHeader(Constant.TRACE_ID);
        if (StringUtils.isEmpty(header)) {
            MDC.put(LogConstant.MDCField.TRACE_ID, dfValueSupplier.get());
        } else {
            MDC.put(LogConstant.MDCField.TRACE_ID, header);
        }
    }


    /**
     * 删除 MDC中的traceId
     */
    public static void removeTraceId() {
        MDC.remove(LogConstant.MDCField.TRACE_ID);
    }


}
